/*
 * @Description:
 * @Version: 2.0
 * @Autor: snzo.chen
 * @Date: 2023-11-20 09:16:41
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-12-20 16:17:41
 */
import { defineStore } from 'pinia';
import { RouteRecordRaw } from 'vue-router';
import { store } from '@/store';
import { login } from '@/api/login';
import { Storage } from '@/utils/Storage';
import { IS_LOGGED_IN } from '@/enums/cacheEnum';
import { generatorDynamicRouter } from '@/router/generator-router';

interface UserState {
  isLoggedIn: boolean;
  username: string;
  roles: API.RoleItem[];
  menus: RouteRecordRaw[];
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    isLoggedIn: Storage.get(IS_LOGGED_IN, null),
    username: 'test_user',
    roles: [],
    menus: [],
  }),
  getters: {
    getIsLoggedIn(): boolean {
      return this.isLoggedIn;
    },
    getName(): string {
      return this.username;
    },
  },
  actions: {
    /** 清空token及用户信息 */
    resetIsLoggedIn() {
      this.username = '';
      this.isLoggedIn = false;
      Storage.clear();
    },
    /** 登录成功保存token */
    setIsLoggedIn(isLoggedIn: boolean) {
      this.isLoggedIn = isLoggedIn ?? false;
      const ex = 7 * 24 * 60 * 60 * 1000;
      Storage.set(IS_LOGGED_IN, this.isLoggedIn, ex);
    },
    /** 登录 */
    async login(params: API.LoginParams) {
      try {
        const { msg } = await login(params);
        this.setIsLoggedIn(true);
        return { msg };
      } catch (error) {
        return Promise.reject(error);
      }
    },
    /** 登录成功之后, 获取用户信息以及生成权限路由 */
    async afterLogin() {
      try {
        // this.name = userInfo.name;
        // 生成路由
        const { menus } = await generatorDynamicRouter();
        this.menus = menus;
        // this.roles = generatorResult.menus.filter(
        //   (item) => !item.meta?.hideInMenu
        // );
        return { menus };
      } catch (error) {
        return Promise.reject(error);
        // return this.logout();
      }
    },
    /** 登出 */
    async logout() {
      // await logout();
      this.resetIsLoggedIn();
    },
  },
});

// 在组件setup函数外使用
export function useUserStoreWithOut() {
  return useUserStore(store);
}
